package com.gzhu.knowledgeAdmin.common.utils;

import com.gzhu.knowledgeAdmin.common.constant.RoleType;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.entity.SecurityUser;
import com.gzhu.knowledgeAdmin.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

/**
 * @author laoba
 * @create 2023-09-12 22:40
 *
 * 获取用户信息工具类
 */
public class UserInfoUtils {

    /**
     * 获取在security上下文信息中保存的的loginUser中的User对象
     * @return loginUser
     */
    public static User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

        //保证返回的loginUser存在的
        if (securityUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return securityUser.getCurrentUserInfo();
    }

    public static List<String> getPermissionList(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

        //保证返回的loginUser存在的
        if (securityUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return securityUser.getPermissionValueList();
    }

    public static void hasOperationPermission(String gsid) {

        User currentUser = getCurrentUser();
        // 通过哪些字段判断是管理员
        if (RoleType.SYS_ADMIN != currentUser.getYhlx()) {
            //不是管理员,则验证该用户的gsid是否和传入的gsid相同
            String currentUserGSID = currentUser.getGsid();
            if (!gsid.equals(currentUserGSID)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }

    }
}
